﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace THO7AlgoritmTimerApplication {
    class Cropwhite : VisionAlgorithm {
        public Cropwhite(String name) : base(name) { }
        public override Bitmap DoAlgorithm(Bitmap sourceImage) {
            BitmapData bmpdata = sourceImage.LockBits(new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            IntPtr ptr = bmpdata.Scan0;
            int regellengte = Math.Abs(bmpdata.Stride);
            int bytes = regellengte * sourceImage.Height;
            byte[] rgbValues = new byte[bytes];
            byte[] output = new byte[bytes];
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
            int new_width = 0;
            int new_height = 0;
            for (int regelnummer = 0; regelnummer < sourceImage.Height-1; regelnummer++) {
                for (int convolutie = 0; convolutie < regellengte; convolutie += 3) {
                    int pixel = regelnummer * regellengte + convolutie;
                    if (rgbValues[pixel] < 1 && rgbValues[pixel + 1] < 1 && rgbValues[pixel + 2] < 1) {
                        for (int c = 0; c < regellengte; c += 3) {
                            int p = regelnummer * regellengte + c;
                            int new_pixel = new_height * regellengte + c;
                            output[new_pixel] = rgbValues[p];
                            output[new_pixel + 1] = rgbValues[p + 1];
                            output[new_pixel + 2] = rgbValues[p + 2];
                        }
                        new_height++;
                        break;
                    }
                }
            }
            new_width = sourceImage.Width;
            if (new_height == 0) {
                new_height = 1;
            }
            Bitmap dest = new Bitmap(new_width, new_height);
            BitmapData bmpdata1 = dest.LockBits(new Rectangle(0, 0, new_width, new_height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
            IntPtr ptr1 = bmpdata1.Scan0;
            System.Runtime.InteropServices.Marshal.Copy(output, 0, ptr1, (new_height * regellengte));
            sourceImage.UnlockBits(bmpdata);
            dest.UnlockBits(bmpdata1);
            return dest;
        }
    }
}
